package edu.ou.herbarium.threads2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import edu.ou.herbarium.sharedata.ErrorData;
import edu.ou.herbarium.sharedata.ShareData1;
import edu.ou.herbarium.sharedata.ShareData2;

public class ServerThread extends Thread{
	private ShareData1 s1;
	private ShareData2 s2;
	private ErrorData de;
	private static int clientId = 100;
	private ArrayList<String> portBuffer = new ArrayList<String>();
	public static ArrayList<ClientThread> clients = new ArrayList<ClientThread>();
	public ServerThread(ShareData1 s1, ErrorData de){
		this.s1 = s1;
		this.de = de;
	}
	
	public void run(){
		try {
			ServerSocket serverSocket = new ServerSocket(60789);
			while(true){
				Socket client = serverSocket.accept();
				String address = new String(client.getInetAddress().getHostAddress());
				boolean flag = true;
				String port = client.getPort()+"";
				for(String str : portBuffer){
					if(str.equals((client.getPort()-1)+"")){
						flag = false;
						portBuffer.remove(str);
						break;
					}
				}
				if(flag){
					String info = address+":"+port;
					de.setShareData("INFO_CLIENT_"+clientId+"::"+info);
					
					
					ClientThread loader = new ClientThread(this.s1,client,de,clientId);
					clients.add(loader);
					portBuffer.add(client.getPort()+"");
					loader.start();
					clientId++;
				}
				else{
					ShareData2 s2 = null;
					for(ClientThread c : clients){
						if(((c.getConnectionSocket().getPort()+1)+"").equals(port)){
							s2 = c.getS2();
							break;
						}
					}
					if(s2!=null){
						ClientThread2 loader = new ClientThread2(s2,client,de,clientId-1);
						loader.start();
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public ShareData2 getS2() {
		return s2;
	}

	public void setS2(ShareData2 s2) {
		this.s2 = s2;
	}

	
}
